import { createRouter,createWebHistory} from "vue-router";
import nprogress from "@/utils/nprogress";
import Messager from '@/utils/messager';

import useMenu from '@/store/menu'

import pinia from '@/store'
import useUser from '@/store/user'
const userStore = useUser(pinia) // 此处不能像在组件里使用userStore一样直接useUser()调用，而是要先引入pinia，再传入。参考： https://blog.csdn.net/qq_21473443/article/details/126405859
console.log('router->userStore',userStore);

const menuStore = useMenu(pinia)


// 路由信息
const routes = [
    {
        path: "/login",
        name: "login",
        component:  () => import('@/views/login/index.vue'),
    },
    {
        path: '/',
        name: 'layout',
        component: ()=>import('@/layout/index.vue'),
        children: []
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
});

function existRoutePath(path) {
    let routes = router.getRoutes()
    let routePathArr = []
    routes.forEach((route) => {
        routePathArr.push(route.path)
    })
    return routePathArr.indexOf(path)
}

router.beforeEach((to,from,next)=>{
    nprogress.start()
    // console.log(router.getRoutes(),existRoutePath(to.path),'router hasRoute-3',to);
    // debugger
    let token = userStore.token
    if(!token) {
        if(to.path == '/login') {
            next()
        } else {
            next('/login')
        }
    } else {
        if(!menuStore.routesMenusLoaded) {
            // console.log(router.getRoutes(),existRoutePath(to.name),'router hasRoute-1',to);
            menuStore.loadRoutesMenus().then(res=>{
                // console.log(router.getRoutes(),existRoutePath(to.name),'router hasRoute-2',to);
                next({...to})
            }).catch(err=>{
                // 加载出错，跳回到登录页去
                userStore.clearUserInfo()
                nprogress.done()
                next('/login')
            })
        } else {
            if(to.path == '/login') {
                Messager.warn('你已登录!')
                next('/home')
            } else {
                // console.log(router.getRoutes(),existRoutePath(to.name),'router hasRoute-4');
                next()
            }
        }
    }

})

router.afterEach((to,from,next)=>{
    nprogress.done()
})

// 导出路由
export default router;